package cn.com.startai.smartadh5.main.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Process;
import android.support.v4.util.LruCache;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Scroller;

import com.blankj.utilcode.util.ScreenUtils;
import com.bumptech.glide.Glide;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import cn.com.startai.smartadh5.db.db.entity.PlayInfo;

/**
 * Describe the function of the class
 *
 * @author zhujinlong@ichoice.com
 * @date 2016/10/22
 * @time 9:21
 * @description Describe the place where the class needs to pay attention.
 */
public class BannerLayout extends FrameLayout {

    ViewPager viewPager;
    private BannerAdapter mBannerAdapter;
    LinearLayout linearLayout;
    GradientDrawable defaultDrawable, selectedDrawable;

    OnPagerClickListener onPagerClickListener;
    private List<PlayInfo> datas = new ArrayList<>();

    int size, gravity, startX, startY;
    boolean isPlaying;

    private ImageLoader imageLoader;
    private OnPlayStateChangedListener mOnPlayStateChangedListener;
    private int curPosition;
    private int loopMode;

    public interface OnPagerClickListener {

        void onClick(PlayInfo entity);
    }

    private Handler handler = new Handler();

    private Runnable playTask = new Runnable() {

        @Override
        public void run() {
            viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
            handler.postDelayed(this, 5000);
        }
    };

    public BannerLayout(Context context) {
        this(context, null);
    }

    public BannerLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BannerLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        imageLoader = new ImageLoader();
        size = (int) (6 * context.getResources().getDisplayMetrics().density + 0.5f);
        gravity = Gravity.CENTER;
        defaultDrawable = new GradientDrawable();
        defaultDrawable.setSize(size, size);
        defaultDrawable.setCornerRadius(size);
        defaultDrawable.setColor(0xffffffff);
        selectedDrawable = new GradientDrawable();
        selectedDrawable.setSize(size, size);
        selectedDrawable.setCornerRadius(size);
        selectedDrawable.setColor(0xff0094ff);

        viewPager = new ViewPager(context);
        LayoutParams vpLayoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        linearLayout = new LinearLayout(context);
        linearLayout.setOrientation(LinearLayout.HORIZONTAL);
        LayoutParams linearLayoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        linearLayout.setGravity(gravity);
        linearLayout.setPadding(size * 2, size * 2, size * 2, size * 2);
        linearLayoutParams.gravity = Gravity.BOTTOM;

        mBannerAdapter = new BannerAdapter(datas);
        viewPager.setAdapter(mBannerAdapter);
        addView(viewPager, vpLayoutParams);
        addView(linearLayout, linearLayoutParams);
        // 修改滚动速度
        Scroller scroller = new Scroller(context) {
            @Override
            public void startScroll(int startX, int startY, int dx, int dy) {
                super.startScroll(startX, startY, dx, dy, 500);
            }

            @Override
            public void startScroll(int startX, int startY, int dx, int dy, int duration) {
                super.startScroll(startX, startY, dx, dy, 500);
            }
        };

        try {
            Field field = viewPager.getClass().getDeclaredField("mScroller");
            field.setAccessible(true);
            field.set(viewPager, scroller);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 监听,切换圆点
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                curPosition = position;
//                if (linearLayout != null && linearLayout.getChildCount() > 0) {
//                    int index = position % datas.size();
//                    for (int i = 0; i < linearLayout.getChildCount(); i++) {
//                        ((ImageView) linearLayout.getChildAt(i)).setImageDrawable(i == index ? selectedDrawable : defaultDrawable);
//                    }
//                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

    }

    public ViewPager getViewPager() {
        return viewPager;
    }

    //设置播放模式
    public void setLoopMode(int loopMode) {
        this.loopMode = loopMode;
    }

    public void next(){
        handler.removeCallbacks(playTask);
        viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
        handler.postDelayed(playTask, 5000);
    }

    public void pre(){
        handler.removeCallbacks(playTask);
        viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
        handler.postDelayed(playTask, 5000);
    }

    public void setOnPagerClickListener(OnPagerClickListener onPagerClickListener) {
        this.onPagerClickListener = onPagerClickListener;
    }

    public synchronized void setPlaying(boolean playing) {
        if (!isPlaying && playing && viewPager.getAdapter() != null && viewPager.getAdapter().getCount() > 2) {
            handler.postDelayed(playTask, 5000);
            isPlaying = true;
            if(mOnPlayStateChangedListener != null) {
                mOnPlayStateChangedListener.onPlay(curPosition);
            }
        } else if (isPlaying && !playing) {
            handler.removeCallbacksAndMessages(null);
            isPlaying = false;
            if(mOnPlayStateChangedListener != null) {
                mOnPlayStateChangedListener.onPause(curPosition);
            }
        }
    }

    public int setDatas(List<PlayInfo> datas) {
        setPlaying(false);
        this.datas.clear();
        linearLayout.removeAllViews();
        if (datas != null) {
            this.datas.addAll(datas);
        }
        mBannerAdapter.setData(datas);
        viewPager.setAdapter(mBannerAdapter);
//        mBannerAdapter.notifyDataSetChanged();
        if (this.datas.size() > 1) {
            viewPager.setCurrentItem(0, false);
//            for (int i = 0; i < this.datas.size(); i++) {
//                ImageView img = new ImageView(getContext());
//                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//                lp.leftMargin = size / 2;
//                lp.rightMargin = size / 2;
//                img.setImageDrawable(i == 0 ? selectedDrawable : defaultDrawable);
//                linearLayout.addView(img, lp);
//            }
            setPlaying(true);
        }
        return this.datas.size();
    }

    public void appendData(List<PlayInfo> datas) {
        if (datas == null || datas.isEmpty()) {
            return;
        }
        this.datas.addAll(datas);
        mBannerAdapter.notifyDataSetChanged();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startX = (int) ev.getX();
                startY = (int) ev.getY();
                getParent().requestDisallowInterceptTouchEvent(true);
                setPlaying(false);
                break;
            case MotionEvent.ACTION_MOVE:
                int moveX = (int) ev.getX();
                int moveY = (int) ev.getY();
                int disX = moveX - startX;
                int disY = moveY - startY;
                getParent().requestDisallowInterceptTouchEvent(2 * Math.abs(disX) > Math.abs(disY));
                setPlaying(false);
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                setPlaying(true);
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        setPlaying(true);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        setPlaying(false);
    }

    @Override
    protected void onWindowVisibilityChanged(int visibility) {
        if (visibility == View.GONE) {
            // 停止轮播
            setPlaying(false);
        } else if (visibility == View.VISIBLE) {
            // 开始轮播
            setPlaying(true);
        }
        super.onWindowVisibilityChanged(visibility);
    }

    // 内置适配器
    private class BannerAdapter extends PagerAdapter {

        private SparseArray<ImageView> imgs = new SparseArray<>();
        private List<PlayInfo> playList;

        public BannerAdapter(List<PlayInfo> playList) {
            this.playList = playList;
        }

        public void setData(List<PlayInfo> playList) {
            this.playList = playList;
        }

        @Override
        public int getCount() {
            return playList == null ? 0 : playList.size() < 2 ? playList.size() : Integer.MAX_VALUE;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            // 解决数据长度为2时左滑出现空白的问题
            final int realPosition = position % playList.size();
            int index = position % (playList.size() * (playList.size() == 2 ? 2 : 1));
            ImageView imageView = imgs.get(index);
            if (imageView == null) {
                imageView = new ImageView(container.getContext());
                imageView.setLayoutParams(new ViewPager.LayoutParams());
                imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
                imgs.put(index, imageView);
            }


            imageLoader.loadImage(imageView, playList.get(realPosition).getFilePath());
            ViewParent parent = imageView.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(imageView);
            }
            container.addView(imageView);
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            ImageView imageView = imgs.get(position);
            if (imageView!=null){
                container.removeView(imageView);
            }
        }
    }

    private class ImageLoader {
        private HandlerThread mHandlerThread;
        private Handler mWorkHandler;

        private LruCache<String, Bitmap> mBitmapCache;
        private int screenWidth, screenHeight;

        public ImageLoader() {

            // 获取当前进程的可用内存（单位KB）
            int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
            // 缓存大小为当前进程可用内存的1/8
            int cacheSize = maxMemory / 8;
            mBitmapCache = new LruCache<String, Bitmap>(cacheSize) {
                @Override
                protected int sizeOf(String key, Bitmap bitmap) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        return bitmap.getAllocationByteCount() / 1024;
                    } else {
                        return bitmap.getByteCount() / 1024;
                    }
                }

                @Override
                protected void entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue) {
                    super.entryRemoved(evicted, key, oldValue, newValue);
//                    if (oldValue != null) {
//                        oldValue.recycle();
//                    }
                }
            };

            mHandlerThread = new HandlerThread("[BannerLayout.ImageLoader.mHandlerThread]",
                    Process.THREAD_PRIORITY_BACKGROUND);
            mHandlerThread.start();
            mWorkHandler = new Handler(mHandlerThread.getLooper());

            screenWidth = ScreenUtils.getScreenWidth();
            screenHeight = ScreenUtils.getScreenHeight();
        }

        void loadImage(ImageView target, String path) {
            mWorkHandler.post(new Runnable() {
                @Override
                public void run() {
                    Bitmap bitmap = mBitmapCache.get(path);
                    path.replace(" ","");
//                    if (bitmap == null) {
//                        try {
//                            bitmap = ImageUtils.getBitmap(path, screenWidth, screenHeight);
//                            Log.i("BannerLayout","screenWidth="+screenWidth+"  "+"screenHeight="+screenHeight);
//                            Log.i("BannerLayout","path ="+path +"bitmap="+bitmap);
//                            mBitmapCache.put(path, bitmap);
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                            post(new Runnable() {
//                                @Override
//                                public void run() {
//                                    Glide.with(getContext()).load(path).into(target);
//                                }
//                            });
//
//
//                        }
//
//                    }
                    Bitmap finalBitmap = bitmap;
                    post(new Runnable() {
                        @Override
                        public void run() {
//                            target.setImageBitmap(finalBitmap);
                            Glide.with(getContext()).load(path).into(target);
                        }
                    });
                }
            });
        }
    }


    public void setOnPlayStateChangedListener(OnPlayStateChangedListener l) {
        mOnPlayStateChangedListener = l;
    }

    public interface OnPlayStateChangedListener {
        void onPlay(int position);
        void onPause(int position);
    }
}